package com.stormrage.xiangyu.view;

import android.Manifest;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.stormrage.xiangyu.R;
import com.stormrage.xiangyu.plugin.Xiangyu;
import com.tencent.ilivesdk.business.callbusiness.ILVCallListener;
import com.tencent.ilivesdk.business.callbusiness.ILVCallManager;
import com.tencent.ilivesdk.business.callbusiness.ILVCallOption;

import org.xutils.common.Callback;
import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;

import static com.tencent.qalsdk.service.QalService.context;

public class NewCallActivity extends Activity implements ILVCallListener {

    private int callId;
    private int callType;
    private String fromUserId;
//    private String strCustom;

    private Button refuse,accept;
    private TextView callname;
    private CircleImageView peericon;
    private MediaPlayer mMediaPlayer;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_call);

        // 添加通话回调
        ILVCallManager.getInstance().addCallListener(this);

        callId = getIntent().getIntExtra("callId",0);
        Log.i("callId","callId:"+callId);
        callType = getIntent().getIntExtra("callType",0);
        fromUserId = getIntent().getStringExtra("fromUserId");
//        strCustom = getIntent().getStringExtra("strCustom");

        callname = (TextView) findViewById(R.id.callname);
//        calloper = (TextView) findViewById(R.id.calloper);
//        callname.setText(fromUserId);
        //来电人的昵称
        callname.setText(getIntent().getStringExtra("nickname"));
        //来电人的头像
        peericon = (CircleImageView) findViewById(R.id.peericon);
        Log.i("url","url-"+getIntent().getStringExtra("iconurl")+"");
        if (getIntent().getStringExtra("iconurl")!=null){
            x.image().loadDrawable(getIntent().getStringExtra("iconurl"), ImageOptions.DEFAULT, new Callback.CommonCallback<Drawable>() {
                @Override
                public void onSuccess(Drawable result) {
                    peericon.setImageDrawable(result);
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });
        }
        refuse = (Button) findViewById(R.id.refuse);
        accept = (Button) findViewById(R.id.accept);
        checkPermission();
        callRing();

        refuse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Xiangyu.getInstance().myNativeToJavascript(1008);
                ILVCallManager.getInstance().rejectCall(callId);
                finish();
            }
        });

        accept.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //接收视频
                Xiangyu.getInstance().myNativeToJavascript(1007);
                ILVCallManager.getInstance().acceptCall(callId, new ILVCallOption(fromUserId).setCallType(callType));
                Intent intent = new Intent();
                intent.setClass(NewCallActivity.this, VideoCallActivity.class);
                intent.putExtra("HostId", fromUserId);
                intent.putExtra("CallId", callId);
                startActivity(intent);
                finish();
            }
        });
    }

    void checkPermission() {
        final List<String> permissionsList = new ArrayList<>();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if ((checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED))
                permissionsList.add(Manifest.permission.CAMERA);
            if ((checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED))
                permissionsList.add(Manifest.permission.RECORD_AUDIO);
            if ((checkSelfPermission(Manifest.permission.WAKE_LOCK) != PackageManager.PERMISSION_GRANTED))
                permissionsList.add(Manifest.permission.WAKE_LOCK);
            if ((checkSelfPermission(Manifest.permission.MODIFY_AUDIO_SETTINGS) != PackageManager.PERMISSION_GRANTED))
                permissionsList.add(Manifest.permission.MODIFY_AUDIO_SETTINGS);
            if ((checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED))
                permissionsList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if ((checkSelfPermission(Manifest.permission.MODIFY_AUDIO_SETTINGS) != PackageManager.PERMISSION_GRANTED))
                permissionsList.add(Manifest.permission.MODIFY_AUDIO_SETTINGS);
            if ((checkSelfPermission(Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS) != PackageManager.PERMISSION_GRANTED))
                permissionsList.add(Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);
            if (permissionsList.size() != 0) {
                requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                        0);
            }
        }
    }


    @Override
    protected void onPause() {
        super.onPause();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mMediaPlayer!=null && mMediaPlayer.isPlaying()){
            mMediaPlayer.stop();
        }
    }

    private void callRing() {
        mMediaPlayer = MediaPlayer.create(this, getSystemDefultRingtoneUri());
        mMediaPlayer.setLooping(true);
        try {
            mMediaPlayer.prepare();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        mMediaPlayer.start();

    }

    private Uri getSystemDefultRingtoneUri() {
        return RingtoneManager.getActualDefaultRingtoneUri(this,
                RingtoneManager.TYPE_RINGTONE);
    }

    @Override
    public void onCallEstablish(int callId) {

    }

    @Override
    public void onCallEnd(int callId, int endResult, String endInfo) {
        Log.i("通话取消","id:"+callId+",code:"+endResult+",info:"+endInfo);
        if (endResult==0){
            Toast.makeText(this,"对方已取消视频通话",Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(this,"取消视频",Toast.LENGTH_SHORT).show();
        }
        this.finish();
    }

    @Override
    public void onException(int iExceptionId, int errCode, String errMsg) {

    }
}
